const { Controller } = require('../lib/contorller');
const { userModel } = require('../lib/mongo');

module.exports = class SsoController extends Controller {
  async get() {
    const { ctx } = this;
    try {
      ctx.result.list = await userModel.find().lean();
      ctx.result.success = true;
    } catch (error) {
      this.log.error(error);
      ctx.result.message = error?.message;
    }
  }

  async add() {
    const { ctx } = this;
    try {
      const { _id, name } = ctx.request.body;
      const user = await userModel.findById(_id);
      if (user) {
        ctx.result.message = '用户已存在！';
        return;
      }
      await userModel.create({ _id, name });
      ctx.result.success = true;
    } catch (error) {
      this.log.error(error);
      ctx.result.message = error?.message;
    }
  }

  async del() {
    const { ctx } = this;
    try {
      const { _id } = ctx.query;
      await userModel.deleteOne({ _id });
      ctx.result.success = true;
    } catch (error) {
      this.log.error(error);
      ctx.result.message = error?.message;
    }
  }
};
